import csv

import requests
import json
import pandas as pd
import time
import os
import csv


# def write_data(file_name, data):
#     path = file_name
#     if os.path.exists(path):
#         print("delete old file before write data")
#         os.remove(path)
#     with open(path, 'a', errors='ignore', newline='') as f:
#         f_csv = csv.writer(f)
#         f_csv.writerows(data)
#         print("Write data success")


number = 1000  # 需要获取的交易日个数
begin = int(time.time() * 1000)
url = 'https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=SZ159915&begin=' + str(
    begin) + '&period=day&type=before&count=-' + str(number)

# F12 使用网络请求头获取
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36 Edg/100.0.1185.29',
    'Cookie': 'device_id=e96689653fa940903140548ad668dab; s=bx13l1ezij; bid=9f0c608e950e1902d00e4ac110b2291f_kzkywcab; __utmz=1.1644741853.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=1.1699306649.1644741853.1644745115.1645878923.3; cookiesu=631648048318219; acw_tc=276077b416491484957935617e35d8dd4b29147f30557519d955c91e8fc3a9; xq_a_token=f1e4545cb0f3cfb17acc98ad7a298b8106f55e86; xqat=f1e4545cb0f3cfb17acc98ad7a298b8106f55e86; xq_r_token=f5d9f889384a1b3b886c6a67f79bd30c74aaeb1c; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTY1MTQ0NzY3MywiY3RtIjoxNjQ5MTQ4NDcwMDMwLCJjaWQiOiJkOWQwbjRBWnVwIn0.dnRWqJgg35hPlx51zpBNyf2kbhYLqEOHdgBRB33qGTyTSVID-CdIcEdg2FdhE0n9EIfCUYAzNkRuqjr2cdiMde_wDmUDrCrogx8qklBh3Eecsex-ed9o1xGSTfnGiLXUaUFpic5YGcRxBZ2GpJ3T3I3G9kbMI3dGZA8AsFGqZtTM85f9i0JOem-KkoIAOdgyhhZcx2PRSeEM5NFfZsri0RRDgTeiOlK69fs_S_4CyqXx-SbY9zVNNPCi7Q1VxgZOnaup554wfELx0WkiA4P-n1Mw-rh9MovqZXy_PubeInj6cEtTdI6ffHCTGN1oDUrz2kZMCOtZ0srAhFoBndZEBQ; u=671649148495815; Hm_lvt_1db88642e346389874251b5a1eded6e3=1648048318,1648282901,1648963700,1649148497; is_overseas=0; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1649148509'}

r = requests.get(url, headers=headers)
text = r.text
data = json.loads(text)
item = data['data']['item']
df = pd.DataFrame(item,
                  columns=["timestamp", "volume", "open", "high", "low", "close", "chg", "percent", "turnoverrate",
                           "amount", "volume_post", "amount_post"])  # list转为DataFrame数据格式，更方便以后的处理
print(df)